package org.csc.sss.datacore.primary.repository.impl;

import org.csc.sss.datacore.dto.SysUserDTO;
import org.csc.sss.datacore.primary.BaseRepositoryImpl;
import org.csc.sss.datacore.primary.model.SysPermission;
import org.csc.sss.datacore.primary.model.SysRolePermission;
import org.csc.sss.datacore.primary.model.SysUser;
import org.csc.sss.datacore.primary.model.SysUserRole;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysUserRepositoryImpl extends BaseRepositoryImpl {

	public Specification<SysUser> sysUserSpecification(SysUserDTO dto){
		return new Specification<SysUser>() {

			@Override
			public Predicate toPredicate(Root<SysUser> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				return null;
			}
		};
	}

	@Transactional()
	public int updateSysUser(SysUser user) {
		return super.sysUserRepository.updateSysUser(new Date(), user.getId());
	}


	/**
	 * 根据userId获取权限
	 * @param userId
	 * @return
	 */
	public List<SysPermission> permissions(@NotNull String userId) {

		List<SysUserRole> userRoles = sysUserRoleRepository.findByUserId(userId);
		if (null == userRoles || userRoles.isEmpty()) {
			return null;
		}
		List<String> roles = new ArrayList<>();
		for (SysUserRole sysUserRole : userRoles) {
			roles.add(sysUserRole.getRoleId());
		}
		List<SysRolePermission> rolePermissions = sysRolePermissionRepository.findByRoleIdIn(roles);
		if (null == rolePermissions || rolePermissions.isEmpty()) {
			return null;
		}
		List<String> permissions = new ArrayList<>();
		for (SysRolePermission sysRolePermission : rolePermissions) {
			permissions.add(sysRolePermission.getPermissionId());
		}
		return sysPermissionRepository.findByIdIn(permissions);
	}
}
